package project.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import project.pojo.CourseForSelect;
import project.service.StudentService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/StudentQueryServlet")
public class StudentQueryServlet extends HttpServlet {
    StudentService service = new StudentService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        long user_id = Long.parseLong(request.getParameter("user_id"));
        String q = request.getParameter("q");
        if ("select".equals(q)){
            String selectQueryJSON = request.getParameter("query");
            CourseForSelect courseForSelect = JSON.parseObject(selectQueryJSON, CourseForSelect.class);
            List<CourseForSelect> courses = service.queryAllByInformation(user_id,courseForSelect.getId(),courseForSelect.getName(),courseForSelect.getTeacherName(),courseForSelect.getTypeStatus());
            service.setValuesCourses(courses,user_id);
            String coursesJSON = JSON.toJSONString(courses);
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(coursesJSON);
        }else if ("password".equals(q)){
            String updatePasswordJSON = request.getParameter("query");
            JSONObject jsonObject = JSON.parseObject(updatePasswordJSON);
            String res = service.updatePassword(user_id, (String)jsonObject.get("oldPassword"), (String)jsonObject.get("password"));
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(res);
        }else if ("email".equals(q)){
            String email = request.getParameter("query");
            String res = service.updateEmail(user_id,email);
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(res);
        }else if ("phone".equals(q)){
            String phone = request.getParameter("query");
            String res = service.updatePhone(user_id,phone);
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(res);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
